package com.zhx.basis.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class 读写锁 {
    private volatile Map map=new HashMap();
    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock();

    public void write(String key,String value) {
        reentrantReadWriteLock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"writing.....");
        try { Thread.sleep(3000); } catch (InterruptedException e) {  e.printStackTrace(); }
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"write done!");
        reentrantReadWriteLock.writeLock().unlock();

    }
    public void read(String key) {
        reentrantReadWriteLock.readLock().lock();
        System.out.println(Thread.currentThread().getName()+"reading.....");
        try { Thread.sleep(3000); } catch (InterruptedException e) {  e.printStackTrace(); }
        map.get(key);
        System.out.println(Thread.currentThread().getName()+"read done!");
        reentrantReadWriteLock.readLock().unlock();
    }

    public static void main(String[] args) {
        读写锁 z=new 读写锁();
        for (int i = 0; i < 3; i++) {
            int temp = i;
            new Thread(()->{
                z.write(temp +"", temp +"==");
            },"线程"+i).start();
        }
        for (int i = 0; i < 3; i++) {
            int temp = i;
            new Thread(()->{
                z.read(temp +"");
            },"线程"+i).start();
        }

    }
}
